const KEY = 'serach_key'
const DATA_MAX = 10

export default {
  namespaced: true,
  state: () => {
    return {
      searchHistoryData: uni.getStorageSync(KEY) || [],
    };
  },
  mutations: {
    //存储数据到本地
    onSaveDataToLocal(state){
      uni.setStorage({
        key:KEY,
        data:state.searchHistoryData
      })

    },
    //添加数据
    onSaveSearchHistory(state, val) {
      const result = state.searchHistoryData.findIndex((item) => item === val);
      if (result !== -1) {
        state.searchHistoryData.splice(result, 1);
      }
      state.searchHistoryData.unshift(val);
      if(state.searchHistoryData.length >DATA_MAX){
        state.searchHistoryData.splice(DATA_MAX,1)
      }
      this.commit('search/onSaveDataToLocal')
    },
    //删除指定数据
    onDeleteSearchItem(state,val) {
      const result = state.searchHistoryData.findIndex((item) => item === val);
      state.searchHistoryData.splice(result, 1);
      this.commit('search/onSaveDataToLocal')
    },
    //删除所有数据
    onDeleteAll(state) {
      state.searchHistoryData = [];
      this.commit('search/onSaveDataToLocal')
    },
  },
};
